<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSDoc: Source: request.js</title>

    <script src="scripts/prettify/prettify.js"> </script>
    <script src="scripts/prettify/lang-css.js"> </script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>

<body>

<div id="main">

    <h1 class="page-title">Source: request.js</h1>

    



    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>/*
 * @Author: cl
 * @Description: 
 * @Date: 2022-10-24 14:40:41
 * @LastEditTime: 2022-10-24 14:41:57
 * @FilePath: \vue3\src\api\request.js
 */
import axios from "axios";
import { Message, MessageBox } from "element-ui";
import store from "@/store";
import router from "@/router";
import { removeToken } from "@/utils/auth";
import { getToken, setToken } from "../utils/auth";
//axios.defaults.withCredentials=true;
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  timeout: 15000 // 请求超时时间
});
/**
 * 请求头
 */
//登录特定token值
const defaultCode =
  "eyJ1c2FnZSI6IkZPUl9MT0dJTiIsInR5cCI6IkpXVCIsImFsZyI6IkhTMjU2In0.eyJleHAiOjMxMzM2MzA5NDQwMCwidXNlcl91aWQiOjF9.eW8qNRbl_ac4Ky2gpFWqG3fbkmJv_NFcxjhlsZ_CJDQ";
const header = () => {
  const config_ = {
    "X-AUTH-TOKEN": ""
  };
  config_["X-AUTH-TOKEN"] = getToken() || defaultCode;
  return config_;
};
// request拦截器
service.interceptors.request.use(
  config => {
    const config_ = header();
    config.headers["X-AUTH-TOKEN"] = config_["X-AUTH-TOKEN"];
    // 增加get请求参数：时间戳
    if (config.method === "get") {
      config.params = {
        timestamp: Date.parse(new Date()) / 1000,
        ...config.params
      };
    }
    return config;
  },
  error => {
    Promise.reject(error);
  }
);
//判断对象里是否有某个属性
function hasProperty(obj, key) {
  return key in obj;
}
// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response;
    //headers是否存在X-AUTH-RENEW，若存在更新token
    let authrenew = hasProperty(res.headers, "x-auth-renew");
    if (authrenew) {
      setToken(res.headers["x-auth-renew"]);
    }
    if (res.data.success) {
      return response;
    } else {
      switch (res.data.errCode) {
        case 10007:
          Message.closeAll();
          Message({
            message: res.data.errMessage,
            type: "error",
            duration: 3 * 1000
          });
          return response; // 用于更换验证码
        case 56001:
          return response;
        case 99999:
          Message.closeAll();
          Message({
            message: "服务器访问异常，请稍后重试!",
            type: "error",
            duration: 3 * 1000
          });
          return response;

        // break;
        case 10001:
        case 10002:
        case 10004:
        case 10005:
          MessageBox({
            title: "登录已过期",
            type: "warning",
            message: "很抱歉，登录已过期，请重新登录",
            confirmButtonText: "重新登录",
            showClose: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            duration: 3 * 1000,
            callback: () => {
              //
              store
                .dispatch("LogOut")
                .then(() => {
                  location.reload();
                })
                .catch(() => {
                  removeToken();
                  location.reload();
                });
            }
          });
          break;
        case -1001:
          return response;
        default:
          // 这里除了目前文档定义好的编码后台还会不定的加其他错误编码编码
          Message.closeAll();
          Message({
            message: res.data.errMessage,
            type: "error",
            duration: 3 * 1000
          });
          return response;
      }
    }
  },
  error => {
    if (error &amp;&amp; error.response) {
      switch (error.response.status) {
        case 400:
          // error.message = '请求错误(400)';
          router.push({ name: "error_400" });
          break;

        case 401:
          // error.message = '未授权，请重新登录(401)';
          removeToken();
          router.push({ path: "/login" });
          break;

        case 403:
          // error.message= '拒绝访问(403)';
          removeToken();
          router.push({ path: "/login" });
          break;

        case 404:
          // error.message= '请求出错(404)';
          router.push({ name: "error_404" });
          break;

        case 408:
          // error.message= '请求超时(408)';
          router.push({ name: "error_408" });
          break;

        case 500:
          // // error.message= '服务器错误(500)';
          router.push({ name: "error_500" });
          break;

        case 501:
          // error.message= '服务未实现(501)';
          router.push({ name: "error_501" });
          break;

        case 502:
          // error.message= '网络错误(502)';
          router.push({ name: "error_502" });

          break;

        case 503:
          // error.message= '服务不可用(503)';
          router.push({ name: "error_503" });
          break;

        case 504:
          // error.message= '网络超时(504)';
          router.push({ name: "error_504" });
          break;

        case 505:
          // error.message= 'HTTP版本不受支持(505)';
          router.push({ name: "error_505" });
          break;

        default:
          error.message = `连接出错(${error.response.status})!`;
      }
    } else {
      if (error.message.includes("timeout")) {
        Message.closeAll();
        Message({
          message: "网络异常，请稍后重试!",
          type: "error",
          duration: 6 * 1000
        });
      } else {
        Message.closeAll();
        Message({
          message: error.message,
          type: "error",
          duration: 6 * 1000
        });
      }
    }
    if (error.message.includes("timeout")) {
      return Promise.reject("网络异常，请稍后重试!");
    } else {
      return Promise.reject(error);
    }
  }
);
export default service;</code></pre>
        </article>
    </section>




</div>

<nav>
    <h2><a href="index.html">Home</a></h2><h3>Global</h3><ul><li><a href="global.html#defaultCode">defaultCode</a></li></ul>
</nav>

<br class="clear">

<footer>
    Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 4.0.2</a> on Mon Oct 23 2023 17:21:58 GMT+0800 (中国标准时间)
</footer>

<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>
